<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { RouterLink, useRouter } from 'vue-router'
import { useCartStore } from '../stores/cart'
import { useUserStore } from '../stores/user'

const router = useRouter()
const cartStore = useCartStore()
const userStore = useUserStore()

// 购物车项是否全部选中
const allSelected = ref(false)

// 获取购物车项目
const cartItems = computed(() => cartStore.items)

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.price * item.quantity, 0)
    .toFixed(2)
})

// 计算选中的商品数量
const selectedCount = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.quantity, 0)
})

// 计算购物车总数量
const cartTotalCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

// 监听购物车变化，更新全选状态
watch(cartItems, () => {
  updateAllSelectedState()
}, { deep: true })

// 更新全选状态
const updateAllSelectedState = () => {
  if (cartItems.value.length === 0) {
    allSelected.value = false
  } else {
    allSelected.value = cartItems.value.every(item => item.selected)
  }
}

// 切换全选/取消全选
const toggleAllSelected = () => {
  allSelected.value = !allSelected.value
  cartItems.value.forEach(item => {
    item.selected = allSelected.value
  })
  cartStore.saveCart()
}

// 切换单个商品选中状态
const toggleItemSelected = (itemId) => {
  const item = cartItems.value.find(i => i.id === itemId)
  if (item) {
    item.selected = !item.selected
    updateAllSelectedState()
    cartStore.saveCart()
  }
}

// 更新商品数量
const updateQuantity = (itemId, delta) => {
  const item = cartItems.value.find(i => i.id === itemId)
  if (item) {
    const newQuantity = item.quantity + delta
    if (newQuantity >= 1 && (!item.stock || newQuantity <= item.stock)) {
      item.quantity = newQuantity
      cartStore.saveCart()
    }
  }
}

// 删除购物车项
const removeFromCart = (itemId) => {
  if (confirm('确定要从购物车中移除该商品吗？')) {
    cartStore.removeFromCart(itemId)
  }
}

// 清空购物车
const clearCart = () => {
  if (confirm('确定要清空购物车吗？')) {
    cartStore.clearCart()
  }
}

// 继续购物
const continueShopping = () => {
  router.push('/products')
}

// 去结算
const goToCheckout = () => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }
  
  const selectedItems = cartItems.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    alert('请选择要结算的商品')
    return
  }
  
  router.push('/checkout')
}

// 加载购物车数据
onMounted(async () => {
  if (userStore.isLoggedIn) {
    await cartStore.loadCart()
  }
})
</script>

<template>
  <main class="cart-container">
    <div class="container">
      <h1 class="page-title">我的购物车</h1>
      
      <!-- 购物车内容 -->
      <div class="cart-content">
        <!-- 购物车为空 -->
        <div v-if="cartItems.length === 0" class="empty-cart">
          <div class="empty-cart-icon">🛒</div>
          <h2>购物车还是空的</h2>
          <p>快去挑选心仪的商品吧</p>
          <RouterLink to="/products" class="shop-now-btn">立即购物</RouterLink>
        </div>
        
        <!-- 购物车有商品 -->
        <div v-else>
          <!-- 购物车头部 -->
          <div class="cart-header">
            <div class="header-select">
              <input 
                type="checkbox" 
                id="select-all" 
                v-model="allSelected"
                @change="toggleAllSelected"
                class="select-checkbox"
              />
              <label for="select-all" class="select-label">全选</label>
            </div>
            <div class="header-product">商品信息</div>
            <div class="header-price">单价</div>
            <div class="header-quantity">数量</div>
            <div class="header-subtotal">小计</div>
            <div class="header-action">操作</div>
          </div>
          
          <!-- 购物车列表 -->
          <div class="cart-items">
            <div 
              v-for="item in cartItems" 
              :key="item.id" 
              class="cart-item"
            >
              <!-- 选择框 -->
              <div class="item-select">
                <input 
                  type="checkbox" 
                  :id="`select-${item.id}`" 
                  v-model="item.selected"
                  @change="toggleItemSelected(item.id)"
                  class="select-checkbox"
                />
                <label :for="`select-${item.id}`" class="select-label"></label>
              </div>
              
              <!-- 商品信息 -->
              <div class="item-product">
                <RouterLink :to="`/products/${item.productId}`" class="product-link">
                  <img :src="item.image" :alt="item.name" class="product-image" />
                </RouterLink>
                <div class="product-info">
                  <RouterLink :to="`/products/${item.productId}`" class="product-name">
                    {{ item.name }}
                  </RouterLink>
                  <div class="product-spec" v-if="item.spec">规格：{{ item.spec }}</div>
                </div>
              </div>
              
              <!-- 单价 -->
              <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
              
              <!-- 数量控制 -->
              <div class="item-quantity">
                <div class="quantity-control">
                  <button 
                    class="quantity-btn minus" 
                    @click="updateQuantity(item.id, -1)"
                    :disabled="item.quantity <= 1"
                  >
                    -
                  </button>
                  <input 
                    type="number" 
                    :value="item.quantity" 
                    class="quantity-input"
                    :min="1" 
                    :max="item.stock || 99"
                    @change="(e) => {
                      const value = parseInt(e.target.value)
                      if (value >= 1 && (!item.stock || value <= item.stock)) {
                        item.quantity = value
                        cartStore.saveCart()
                      }
                    }"
                  />
                  <button 
                    class="quantity-btn plus" 
                    @click="updateQuantity(item.id, 1)"
                    :disabled="item.stock && item.quantity >= item.stock"
                  >
                    +
                  </button>
                </div>
                <div v-if="item.stock" class="stock-info">
                  库存: {{ item.stock }}
                </div>
              </div>
              
              <!-- 小计 -->
              <div class="item-subtotal">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              
              <!-- 操作 -->
              <div class="item-action">
                <button class="delete-btn" @click="removeFromCart(item.id)">
                  删除
                </button>
              </div>
            </div>
          </div>
          
          <!-- 购物车底部 -->
          <div class="cart-footer">
            <div class="footer-left">
              <button class="clear-cart-btn" @click="clearCart">
                清空购物车
              </button>
              <span class="item-count">共 {{ cartTotalCount }} 件商品</span>
            </div>
            
            <div class="footer-right">
              <div class="total-section">
                <div class="total-label">合计：</div>
                <div class="total-price">¥{{ totalPrice }}</div>
              </div>
              <div class="checkout-section">
                <span class="selected-info">已选 {{ selectedCount }} 件商品</span>
                <button class="checkout-btn" @click="goToCheckout">
                  去结算
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 推荐商品 -->
      <div v-if="cartItems.length === 0" class="recommended-products">
        <h2 class="section-title">猜你喜欢</h2>
        <div class="products-grid">
          <div v-for="(product, index) in [1, 2, 3, 4]" :key="index" class="product-card">
            <RouterLink to="/products" class="product-link">
              <div class="product-image-wrapper">
                <img src="https://picsum.photos/seed/product${index}/400/400" alt="推荐商品" class="product-image" />
              </div>
              <div class="product-info">
                <h3 class="product-name">精选优质商品 #{{ index }}</h3>
                <div class="product-price">¥{{ Math.floor(Math.random() * 1000) + 100 }}</div>
              </div>
            </RouterLink>
          </div>
        </div>
      </div>
    </div>
  </main>
</template>

<style scoped>
.cart-container {
  min-height: calc(100vh - 130px);
  padding: 0;
  background-color: #f8f9fa;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 32px;
  font-weight: 600;
  color: #212529;
  margin-bottom: 30px;
  text-align: center;
  padding: 30px 0 0;
}

.cart-content {
  background-color: #ffffff;
  border-radius: 0;
  overflow: hidden;
}

/* 空购物车样式 */
.empty-cart {
  text-align: center;
  padding: 100px 20px;
  background-color: #ffffff;
}

.empty-cart-icon {
  font-size: 80px;
  margin-bottom: 24px;
  color: #e9ecef;
}

.empty-cart h2 {
  font-size: 28px;
  font-weight: 600;
  color: #212529;
  margin-bottom: 12px;
}

.empty-cart p {
  font-size: 16px;
  color: #6c757d;
  margin-bottom: 30px;
}

.shop-now-btn {
  display: inline-block;
  padding: 14px 32px;
  background-color: #212529;
  color: #ffffff;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  text-decoration: none;
  transition: background-color 0.2s ease;
}

.shop-now-btn:hover {
  background-color: #343a40;
}

/* 购物车头部样式 */
.cart-header {
  display: grid;
  grid-template-columns: 100px 1fr 120px 150px 150px 100px;
  padding: 20px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #dee2e6;
  font-weight: 600;
  color: #212529;
  font-size: 16px;
}

.header-select,
.header-product,
.header-price,
.header-quantity,
.header-subtotal,
.header-action {
  display: flex;
  align-items: center;
}

.header-product {
  padding-left: 20px;
}

/* 购物车项样式 */
.cart-items {
  max-height: 600px;
  overflow-y: auto;
}

.cart-item {
  display: grid;
  grid-template-columns: 100px 1fr 120px 150px 150px 100px;
  padding: 24px;
  border-bottom: 1px solid #e9ecef;
  transition: background-color 0.2s ease;
  background-color: #ffffff;
}

.cart-item:hover {
  background-color: #f8f9fa;
}

/* 选择框样式 */
.item-select {
  display: flex;
  align-items: center;
  justify-content: center;
}

.select-checkbox {
  width: 20px;
  height: 20px;
  cursor: pointer;
  accent-color: #6c757d;
}

.select-label {
  cursor: pointer;
  margin-left: 5px;
  color: #212529;
}

/* 商品信息样式 */
.item-product {
  display: flex;
  align-items: center;
  gap: 20px;
  padding-left: 20px;
}

.product-link {
  text-decoration: none;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: contain;
  background-color: #ffffff;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: #212529;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: color 0.2s ease;
}

.product-name:hover {
  color: #6c757d;
}

.product-spec {
  font-size: 14px;
  color: #6c757d;
}

/* 价格样式 */
.item-price {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

/* 数量控制样式 */
.item-quantity {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.quantity-control {
  display: flex;
  align-items: center;
  width: fit-content;
  background-color: #ffffff;
}

.quantity-btn {
  width: 36px;
  height: 36px;
  border: 1px solid #dee2e6;
  background-color: #f8f9fa;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  color: #495057;
}

.quantity-btn:hover:not(:disabled) {
  background-color: #e9ecef;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background-color: #f8f9fa;
}

.quantity-btn.minus {
  border-radius: 6px 0 0 6px;
}

.quantity-btn.plus {
  border-radius: 0 6px 6px 0;
}

.quantity-input {
  width: 50px;
  height: 36px;
  border: 1px solid #dee2e6;
  border-left: none;
  border-right: none;
  text-align: center;
  font-size: 14px;
  color: #212529;
  background-color: #ffffff;
}

.quantity-input:focus {
  outline: none;
}

.stock-info {
  font-size: 12px;
  color: #999;
}

/* 小计样式 */
.item-subtotal {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

/* 操作样式 */
.item-action {
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-btn {
  padding: 6px 12px;
  border: none;
  background-color: #ffffff;
  color: #6c757d;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 4px;
}

.delete-btn:hover {
  color: #212529;
  background-color: #f8f9fa;
}

/* 购物车底部样式 */
.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px;
  background-color: #ffffff;
  border-top: 1px solid #e9ecef;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.02);
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 30px;
}

.clear-cart-btn {
  padding: 10px 18px;
  border: 1px solid #dee2e6;
  background-color: #ffffff;
  color: #6c757d;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.clear-cart-btn:hover {
  background-color: #f8f9fa;
  border-color: #adb5bd;
  color: #212529;
}

.item-count {
  font-size: 14px;
  color: #6c757d;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 40px;
}

.total-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.total-label {
  font-size: 16px;
  color: #212529;
}

.total-price {
  font-size: 28px;
  font-weight: 600;
  color: #212529;
}

.checkout-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.selected-info {
  font-size: 14px;
  color: #6c757d;
}

.checkout-btn {
  padding: 14px 40px;
  background-color: #212529;
  color: #ffffff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.checkout-btn:hover {
  background-color: #343a40;
}

/* 推荐商品样式 */
.recommended-products {
  margin: 60px 0;
  padding: 40px 0;
  background-color: #f8f9fa;
}

.section-title {
  font-size: 28px;
  font-weight: 600;
  color: #212529;
  margin-bottom: 32px;
  text-align: center;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 30px;
  max-width: 1400px;
  margin: 0 auto;
}

.product-card {
  background-color: #ffffff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  border: 1px solid #e9ecef;
}

.product-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.product-image-wrapper {
  height: 300px;
  overflow: hidden;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-card .product-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.5s ease;
}

.product-card:hover .product-image {
  transform: scale(1.03);
}

.product-card .product-info {
  padding: 20px;
  background-color: #ffffff;
}

.product-card .product-name {
  font-size: 17px;
  font-weight: 500;
  color: #212529;
  margin-bottom: 12px;
  height: 44px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-card .product-price {
  font-size: 21px;
  font-weight: 600;
  color: #212529;
}

/* 响应式设计 */
@media (max-width: 1440px) {
  .container {
    max-width: 1200px;
  }
}

@media (max-width: 1280px) {
  .container {
    max-width: 1100px;
  }
}

@media (max-width: 1024px) {
  .cart-header,
  .cart-item {
    grid-template-columns: 80px 1fr 100px 120px 120px 80px;
  }
  
  .product-image {
    width: 80px;
    height: 80px;
  }
  
  .total-price {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .page-title {
    font-size: 28px;
    padding: 20px 0 0;
  }
  
  .cart-header {
    display: none;
  }
  
  .cart-item {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
    padding: 20px;
    position: relative;
  }
  
  .item-select {
    position: absolute;
    top: 20px;
    left: 20px;
  }
  
  .item-product {
    padding-left: 0;
    margin-left: 40px;
    width: calc(100% - 40px);
  }
  
  .item-quantity,
  .item-price,
  .item-subtotal {
    align-self: flex-end;
  }
  
  .item-action {
    align-self: flex-end;
  }
  
  .cart-footer {
    flex-direction: column;
    gap: 20px;
    padding: 20px 15px;
  }
  
  .footer-left {
    align-self: flex-start;
  }
  
  .products-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    padding: 0 15px;
  }
  
  .section-title {
    font-size: 24px;
    padding: 0 15px;
  }
  
  .product-image-wrapper {
    height: 200px;
  }
}

@media (max-width: 480px) {
  .container {
    padding: 0 15px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .footer-left {
    flex-direction: column;
    align-self: flex-start;
    gap: 10px;
  }
  
  .footer-right {
    flex-direction: column;
    width: 100%;
    gap: 15px;
  }
  
  .checkout-section {
    width: 100%;
    justify-content: space-between;
  }
  
  .checkout-btn {
    padding: 12px 20px;
    font-size: 16px;
  }
  
  .products-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .product-image-wrapper {
    height: 240px;
  }
}
</style>